# coding: utf-8
import time
from threading import Thread

from host import memdb
from host.comunicate import comunicate
from host.settings import HOST, GATHER_INTERVAL
from util.log import logger
from util.send import send_alert


class Comunicate(Thread):
    def __init__(self, ip, config):
        super().__init__()
        self.ip = ip
        self.config = config

    def run(self):
        logger.info('采集任务%s' % self.ip)
        comunicate(self.ip, self.config)
        logger.info('采集完成%s' % self.ip)


class Comunicates(Thread):
    def run(self):
        logger.info('交互线程启动')
        while True:
            for ip, config in HOST.items():
                task = Comunicate(ip, config)
                task.start()
            time.sleep(GATHER_INTERVAL)


class PrintMemdb(Thread):
    def run(self):
        while True:
            for key, value in memdb.ALERT_COMPUTE_TABLE.items():
                print(key, value)
            time.sleep(5)


class SendAlert(Thread):
    def run(self):
        logger.info('告警线程启动')
        while True:
            header, body = memdb.ALERT_TABLE.get()
            logger.info('获取告警:%s,%s' % (header, body))
            send_alert(header, body)


def entry():
    logger.info('主主线程驱动')
    t1 = Comunicates()
    t1.start()
    t3 = SendAlert()
    t3.start()

    return [t1, t3]
